package com.xingge.sdktest.convert;

import com.jolimark.UsbTool;

import java.util.concurrent.LinkedBlockingDeque;

public class PrintThread extends Thread {


    private boolean cancel;
    private PDFCallBack pdfCallBack;
    private LinkedBlockingDeque<PrintTask> taskQueue = new LinkedBlockingDeque<>();

    public synchronized void putTask(PrintTask task) {
        if (cancel)
            return;
        try {
            taskQueue.put(task);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void setPdfCallBack(PDFCallBack callBack) {
        pdfCallBack = callBack;
    }

    public synchronized void cancelTask() {
        cancel = true;
    }

    @Override
    public void run() {
        super.run();
        UsbTool.logd("print thread -> 线程启动");
        boolean ret = true;
        boolean flag_has_work = false;
        while (!cancel) {
            if (!taskQueue.isEmpty()) {
                PrintTask task = taskQueue.poll();
                if (!task.flag_end) {
                    if (pdfCallBack != null) {
                        int len = pdfCallBack.onPageConverted(task.data, task.pageIndex);
                        if (task.data == null || task.data.length == 0 || len != task.data.length)
                            ret = false;
                        if (len > 0)
                            flag_has_work = true;
                    }
                } else {
                    if (pdfCallBack != null) {
                        if (ret && flag_has_work)
                            pdfCallBack.onSuccess();
                        else
                            pdfCallBack.onFail();
                    }
                    UsbTool.logd("print thread -> 全部任务完成，线程结束");
                    break;
                }

            }
        }
        if (cancel) {
            UsbTool.logd("print thread -> 任务取消，清空任务队列，线程结束");
            taskQueue.clear();
            if (pdfCallBack != null)
                pdfCallBack.onCancel();
        }
    }

    static class PrintTask {
        byte[] data;
        int[] pageIndex;
        boolean flag_end;
    }

}
